<template>
  <div class="event-subscription-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          新建订阅
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-space>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索订阅"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="filterStatus"
          placeholder="订阅状态"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option
            v-for="status in subscriptionStatuses"
            :key="status.value"
            :value="status.value"
          >
            {{ status.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 订阅列表 -->
    <a-table
      :columns="columns"
      :data-source="subscriptions"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'eventType'">
          <a-tag :color="getEventTypeColor(record.eventType)">
            {{ getEventTypeLabel(record.eventType) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'enabled'">
          <a-switch
            :checked="record.enabled"
            @change="(checked) => handleToggleEnabled(record.id, checked)"
          />
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">
              编辑
            </a-button>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-popconfirm
              title="确定要删除这个订阅吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 创建/编辑订阅模态框 -->
    <a-modal
      :open="modalVisible"
      :title="editingSubscription ? '编辑事件订阅' : '新建事件订阅'"
      width="800px"
      @ok="handleSave"
      @cancel="closeModal"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="订阅名称" name="name">
              <a-input
                v-model:value="formData.name"
                placeholder="请输入订阅名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="事件类型" name="eventType">
              <a-select
                v-model:value="formData.eventType"
                placeholder="请选择事件类型"
                mode="multiple"
              >
                <a-select-option
                  v-for="type in eventTypes"
                  :key="type.value"
                  :value="type.value"
                >
                  {{ type.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="订阅者类型" name="subscriberType">
              <a-select
                v-model:value="formData.subscriberType"
                placeholder="请选择订阅者类型"
              >
                <a-select-option value="EMAIL">邮件</a-select-option>
                <a-select-option value="WEBHOOK">Webhook</a-select-option>
                <a-select-option value="SMS">短信</a-select-option>
                <a-select-option value="SYSTEM">系统</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="启用状态" name="enabled">
              <a-switch v-model:checked="formData.enabled" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="订阅者地址" name="subscriberAddress">
          <a-input
            v-model:value="formData.subscriberAddress"
            placeholder="请输入订阅者地址（邮箱、URL等）"
          />
        </a-form-item>

        <a-form-item label="过滤条件" name="filterCondition">
          <a-textarea
            v-model:value="formData.filterCondition"
            placeholder="请输入过滤条件（可选）"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="订阅描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入订阅描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 订阅详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="订阅详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="订阅名称">
          {{ selectedSubscription?.name }}
        </a-descriptions-item>
        <a-descriptions-item label="事件类型">
          <a-space>
            <a-tag
              v-for="type in selectedSubscription?.eventType"
              :key="type"
              :color="getEventTypeColor(type)"
            >
              {{ getEventTypeLabel(type) }}
            </a-tag>
          </a-space>
        </a-descriptions-item>
        <a-descriptions-item label="订阅者类型">
          {{ getSubscriberTypeLabel(selectedSubscription?.subscriberType) }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(selectedSubscription?.status)">
            {{ getStatusLabel(selectedSubscription?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="启用状态">
          <a-tag :color="selectedSubscription?.enabled ? 'green' : 'red'">
            {{ selectedSubscription?.enabled ? '启用' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ selectedSubscription?.createdAt }}
        </a-descriptions-item>
        <a-descriptions-item label="订阅者地址" :span="2">
          {{ selectedSubscription?.subscriberAddress }}
        </a-descriptions-item>
        <a-descriptions-item label="过滤条件" :span="2">
          {{ selectedSubscription?.filterCondition || '无' }}
        </a-descriptions-item>
        <a-descriptions-item label="订阅描述" :span="2">
          {{ selectedSubscription?.description }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import type { FormInstance } from 'ant-design-vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'subscription-created': [subscription: any];
  'subscription-updated': [subscription: any];
}>();

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const detailModalVisible = ref(false);
const editingSubscription = ref<any>(null);
const selectedSubscription = ref<any>(null);
const searchKeyword = ref('');
const filterStatus = ref('');
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  name: '',
  eventType: [],
  subscriberType: '',
  subscriberAddress: '',
  filterCondition: '',
  description: '',
  enabled: true,
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入订阅名称' }],
  eventType: [{ required: true, message: '请选择事件类型' }],
  subscriberType: [{ required: true, message: '请选择订阅者类型' }],
  subscriberAddress: [{ required: true, message: '请输入订阅者地址' }],
};

// 事件类型
const eventTypes = [
  { value: 'CREATE', label: '创建事件' },
  { value: 'UPDATE', label: '更新事件' },
  { value: 'DELETE', label: '删除事件' },
  { value: 'START', label: '启动事件' },
  { value: 'STOP', label: '停止事件' },
  { value: 'ERROR', label: '错误事件' },
  { value: 'WARNING', label: '警告事件' },
  { value: 'INFO', label: '信息事件' },
  { value: 'CUSTOM', label: '自定义事件' },
];

// 订阅状态
const subscriptionStatuses = [
  { value: 'ACTIVE', label: '活跃' },
  { value: 'INACTIVE', label: '非活跃' },
  { value: 'ERROR', label: '错误' },
  { value: 'PENDING', label: '待激活' },
];

// 模拟数据
const subscriptions = ref([
  {
    id: '1',
    name: '资源变更通知',
    eventType: ['CREATE', 'UPDATE', 'DELETE'],
    subscriberType: 'EMAIL',
    subscriberAddress: 'admin@example.com',
    filterCondition: 'resource.type === "HOTEL"',
    description: '当酒店资源发生变更时发送邮件通知',
    status: 'ACTIVE',
    enabled: true,
    createdAt: '2024-01-15 10:30:00',
  },
  {
    id: '2',
    name: '系统警告通知',
    eventType: ['WARNING', 'ERROR'],
    subscriberType: 'WEBHOOK',
    subscriberAddress: 'https://api.example.com/webhook/alerts',
    filterCondition: '',
    description: '系统警告和错误事件推送到外部系统',
    status: 'ACTIVE',
    enabled: true,
    createdAt: '2024-01-15 11:00:00',
  },
  {
    id: '3',
    name: '资源状态监控',
    eventType: ['START', 'STOP'],
    subscriberType: 'SMS',
    subscriberAddress: '+86-138-0013-8000',
    filterCondition: 'resource.status === "RUNNING"',
    description: '资源启动和停止时发送短信通知',
    status: 'INACTIVE',
    enabled: false,
    createdAt: '2024-01-15 11:30:00',
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '订阅名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '事件类型',
    dataIndex: 'eventType',
    key: 'eventType',
    width: 200,
  },
  {
    title: '订阅者类型',
    dataIndex: 'subscriberType',
    key: 'subscriberType',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '启用状态',
    dataIndex: 'enabled',
    key: 'enabled',
    width: 100,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 160,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    pagination.value.total = subscriptions.value.length;
    loading.value = false;
  }, 500);
};

const refreshData = () => {
  loadData();
  message.success('数据刷新成功');
};

const handleSearch = (value: string) => {
  searchKeyword.value = value;
  loadData();
};

const handleFilter = (value: string) => {
  filterStatus.value = value;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadData();
};

const showCreateModal = () => {
  editingSubscription.value = null;
  resetFormData();
  modalVisible.value = true;
};

const showEditModal = (record: any) => {
  editingSubscription.value = record;
  Object.assign(formData, record);
  modalVisible.value = true;
};

const showDetailModal = (record: any) => {
  selectedSubscription.value = record;
  detailModalVisible.value = true;
};

const closeModal = () => {
  modalVisible.value = false;
  resetFormData();
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedSubscription.value = null;
};

const resetFormData = () => {
  Object.assign(formData, {
    name: '',
    eventType: [],
    subscriberType: '',
    subscriberAddress: '',
    filterCondition: '',
    description: '',
    enabled: true,
  });
  formRef.value?.clearValidate();
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();

    if (editingSubscription.value) {
      // 更新订阅
      const index = subscriptions.value.findIndex(
        (item) => item.id === editingSubscription.value.id,
      );
      if (index !== -1) {
        subscriptions.value[index] = {
          ...editingSubscription.value,
          ...formData,
        };
      }
      message.success('事件订阅更新成功');
      emit('subscription-updated', formData);
    } else {
      // 创建新订阅
      const newSubscription = {
        id: Date.now().toString(),
        ...formData,
        status: 'ACTIVE',
        createdAt: new Date().toLocaleString(),
      };
      subscriptions.value.unshift(newSubscription);
      message.success('事件订阅创建成功');
      emit('subscription-created', newSubscription);
    }

    closeModal();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleDelete = (id: string) => {
  const index = subscriptions.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    subscriptions.value.splice(index, 1);
    message.success('事件订阅删除成功');
  }
};

const handleToggleEnabled = (id: string, enabled: boolean) => {
  const subscription = subscriptions.value.find((item) => item.id === id);
  if (subscription) {
    subscription.enabled = enabled;
    message.success(`事件订阅已${enabled ? '启用' : '禁用'}`);
  }
};

const getEventTypeLabel = (type: string) => {
  const eventType = eventTypes.find((t) => t.value === type);
  return eventType?.label || type;
};

const getEventTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    CREATE: 'green',
    UPDATE: 'blue',
    DELETE: 'red',
    START: 'cyan',
    STOP: 'orange',
    ERROR: 'red',
    WARNING: 'orange',
    INFO: 'blue',
    CUSTOM: 'purple',
  };
  return colorMap[type] || 'default';
};

const getStatusLabel = (status: string) => {
  const statusItem = subscriptionStatuses.find((s) => s.value === status);
  return statusItem?.label || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    ACTIVE: 'green',
    INACTIVE: 'default',
    ERROR: 'red',
    PENDING: 'orange',
  };
  return colorMap[status] || 'default';
};

const getSubscriberTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    EMAIL: '邮件',
    WEBHOOK: 'Webhook',
    SMS: '短信',
    SYSTEM: '系统',
  };
  return typeMap[type] || type;
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.event-subscription-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }
}
</style>
